package com.swj.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.swj.reggie.common.BaseContext;
import com.swj.reggie.common.R;
import com.swj.reggie.dto.DishDto;
import com.swj.reggie.dto.OrdersDto;
import com.swj.reggie.entity.Employee;
import com.swj.reggie.entity.OrderDetail;
import com.swj.reggie.entity.Orders;
import com.swj.reggie.service.OrderDetailService;
import com.swj.reggie.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 用户下单
     *   http://localhost:8080/order/submit
     *   post {"remark":"","payMethod":1,"addressBookId":"1645408367309537282"}    当前用户userId可以获取到购物车数据
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders){
//        log.info("订单数据：{}",orders);
        orderService.submit(orders);
        return R.success("下单成功");
    }

    /**
     * 订单信息分页查询--用户端
     *  请求 URL: http://localhost:8080/order/userPage?page=1&pageSize=5
     *           http://localhost:8080/order/userPage?page=1&pageSize=1
     *  请求方法: GET
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/userPage")
    public R<Page> userPage(int page, int pageSize){
        Long userId = BaseContext.getCurrentId();
        //构造分页构造器
        Page<Orders> pageInfo = new Page<>(page,pageSize);
        //构造条件构造器
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件
        queryWrapper.eq(Orders::getUserId, userId);
        // 添加排序条件，时间降序，最新下单的排前面----
        queryWrapper.orderByDesc(Orders::getOrderTime);
        //执行查询
        orderService.page(pageInfo,queryWrapper);

        // 分页构造器对象的records属性封装成新的
        List<Orders> orderRecords = pageInfo.getRecords();
        List<OrdersDto> ordersDtoRecords=orderRecords.stream().map(order -> {
            // ordersDto 复制父类对象order的值,ordersDto = order + orderDetail
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(order,ordersDto);

            // ordersDto 拿到OrderDetails 多条订单详细数据 （OrderDetail=order+dish/setmeal）
            Long orderId = order.getId();
            LambdaQueryWrapper<OrderDetail> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(OrderDetail::getOrderId,orderId);
            // SELECT * FROM orderDetail WHERE orderId = ?
            List<OrderDetail> orderDetails = orderDetailService.list(lambdaQueryWrapper);
            ordersDto.setOrderDetails(orderDetails);

            return ordersDto;
        }).collect(Collectors.toList());

        // 构造分页构造器对象
        Page<OrdersDto> ordersDtoPage = new Page<>();
        //对象拷贝，pageInfo里 除了records属性 还有其他属性要复制，如 size、total等
        BeanUtils.copyProperties(pageInfo, ordersDtoPage);    // records属性没有改
        ordersDtoPage.setRecords(ordersDtoRecords);         // records属性设为新的，包含OrderDetail数据

        return R.success(ordersDtoPage);
    }

    /**
     * 订单信息分页查询--管理端    要查到所有用户的订单  select * from orders
     *  请求 URL: 普通无条件查询 http://localhost:8080/order/page?page=1&pageSize=10
     *           订单号查询     http://localhost:8080/order/page?page=1&pageSize=10&number=1646802910
     *           时间区间查询   http://localhost:8080/order/page?page=1&pageSize=10&beginTime=2023-04-07 00:00:00&endTime=2023-05-10 23:59:59
     *           订单号、时间区间查询 .....
     *  请求方法: GET
     * @param page
     * @param pageSize
     * @param beginTime
     * @param endTime
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, Long number, String beginTime, String endTime){
        /*  LocalDateTime是JDK8新增日期类  SimpleDateFormat是JDK8之前就提供了，处理LocalDateTime可能不行
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            LocalDateTime begin = sdf.parse(beginTime); // 接收类型错误
            Date end = sdf.parse(endTime);  // 成功接收
        } catch (ParseException e) {
            e.printStackTrace();
        }*/
       /*  把字符串时间解析成日期对象 String --> LocalDateTime   不需要！！！ 哭了，浪费了时间，算是复习吧
        if (beginTime!=null){
            DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime begin = (LocalDateTime) dtf.parse(beginTime);
            LocalDateTime end = (LocalDateTime) dtf.parse(endTime);
        }*/
        //构造分页构造器
        Page<Orders> pageInfo = new Page<>(page,pageSize);
        //构造条件构造器，拼接条件  1. number like '%?%'  2. orderTime between beginTime and endTime
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(number!=null,Orders::getNumber,number);
        // 前端传来的 beginTime 和 endTime 同时有值或无值
        queryWrapper.between(beginTime!=null,Orders::getOrderTime,beginTime,endTime);
        // 添加排序条件，时间降序，最新下单的排前面----
        queryWrapper.orderByDesc(Orders::getOrderTime);
        //执行查询
        orderService.page(pageInfo,queryWrapper);

        return R.success(pageInfo);
    }


    /**
     * 修改订单状态
     * 请求 URL: http://localhost:8080/order
     * 请求方法: PUT
     * 请求体: {"status":x,"id":"1646504436277723138"}
     * @param orders
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody Orders orders){
        // 根据id修改该行订单的status字段 update orders set status = x where id = x
        LambdaUpdateWrapper<Orders> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(Orders::getStatus,orders.getStatus()).eq(Orders::getId,orders.getId());
        orderService.update(updateWrapper);
        return R.success("操作成功");
    }

}